package wangwenjun.phase1.synchronizeddemo.caslock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ChangLiang
 * @date 2020/6/20
 */
@Slf4j
public class CompareAndSetLock {

    private final AtomicInteger value = new AtomicInteger(0);

    /**
     * 当前拥有锁的thread
     */
    private Thread currentThread;

    public void tryLock() throws TryLockException {
        boolean isSuccess = value.compareAndSet(0, 1);
        if (!isSuccess) {
            throw new TryLockException("try to get lock failed");
        }
        currentThread = Thread.currentThread();
        log.info(Thread.currentThread() + " get the lock.");
    }

    public void unlock() {
        if (0 == value.get()) {
            return;
        }
        if (currentThread == Thread.currentThread()) {
            value.compareAndSet(1, 0);
            log.warn(Thread.currentThread() + " release the lock.");
        }
    }
}
